package com.coffee.admin.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.platform.result.PlatformResult;
import com.coffee.admin.api.platform.service.PlatformPermissionService;
import com.coffee.admin.api.platform.service.PlatformService;
import com.coffee.admin.utils.ProfileUtil;
import com.coffee.core.anotation.PlatformLoginCheck;
import com.coffee.core.entity.LoginUser;
import com.coffee.core.entity.SiteContextThreadLocal;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.result.Result;
import com.coffee.core.util.WebUtil;
import com.coffee.admin.api.common.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class PlatformCheckInterceptor implements HandlerInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(PlatformCheckInterceptor.class);

    @Value("${parameter.webDomain}")
    private String backstageDomain;

    @DubboReference(check = false)
    private RedisService redisService;

    @DubboReference(check = false)
    private PlatformPermissionService platformPermissionService;
    @DubboReference(check = false)
    private PlatformService platformService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws IOException, BusinessException {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        // 开发环境不用校验状态
        if (ProfileUtil.isDevProfile()) {
            return true;
        }

        // 登录状态校验
        PlatformLoginCheck platformLoginCheck = handlerMethod.getMethodAnnotation(PlatformLoginCheck.class);
        if (platformLoginCheck == null) {
            // 不需要校验登录状态
            return true;
        }

        boolean isLogin = isLogin();

        //未登录处理
        if (!isLogin) {
            if (WebUtil.isAjaxRequest(request, response, handlerMethod)) {
                response.setContentType("application/json;charset=UTF-8");
                Map<String, Object> data = notLoginRes();
                response.getWriter().write(JSONObject.toJSONString(data));
            } else {
                response.sendRedirect(backstageDomain);
            }

            return false;
        }


        //权限处理
        String methodAlias = platformLoginCheck.alias();
        if (StringUtils.isEmpty(methodAlias)) {
            return true;
        }

        String mtoken = SiteContextThreadLocal.get().getStoken();
        if (StringUtils.isEmpty(mtoken)) {
            return false;
        }
        String loginUserStr = (String) redisService.get(mtoken);
        LoginUser loginUser = JSONObject.parseObject(loginUserStr, LoginUser.class);
        Integer platformId = loginUser.getPlatformUserId();
        //未登录处理
        if (platformId == null) {
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> data = notLoginRes();
            response.getWriter().write(JSONObject.toJSONString(data));
        }

        String isAdmin = loginUser.getPlatformIsAdmin();
        //超级管理员
        if ("Y".equals(isAdmin)) {
            return true;
        }
        PlatformResult platformResult = platformService.getDetail(platformId);
        if (!"Y".equals(platformResult.getIsEnable())){
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> data = notLoginRes();
            response.getWriter().write(JSONObject.toJSONString(data));
        }

        Set<String> permSet = platformPermissionService.getPermissionSet(platformId);
        //判断是否有该权限
        if (permSet.contains(methodAlias)) {
            return true;
        } else {
            String visitUrl = request.getRequestURI();
            LOG.info("***** uri:" + visitUrl + " ,platformId:" + platformId + " 没有权限 :  " + methodAlias);
            write(response, ExceptionEnum.ERROR_200014);
        }
        return false;
    }

    private void write(HttpServletResponse response, ExceptionEnum exceptionEnum) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Result<Object> data = Result.failed(exceptionEnum);
        response.getWriter().write(JSONObject.toJSONString(data));
    }


    private boolean isLogin() {
        String mtoken = SiteContextThreadLocal.get().getStoken();
        if (StringUtils.isEmpty(mtoken)) {
            return false;
        }

        boolean hasKey = redisService.hasKey(mtoken);
        if (!hasKey) {
            return false;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) {
    }


    private Map<String, Object> notLoginRes() {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("isLogin", false);
        data.put("code", "unLogin");
        data.put("msg", "您还尚未登录");
        return data;
    }
}
